#!/usr/bin/perl -w

use strict;

use File::Copy;
use File::Basename;
use File::Path;
use File::Spec;
use IO::Compress::Zip qw(zip $ZipError);
use Archive::Zip;

my $CHROME = "C:/Documents and Settings/quan.gan/Local Settings/Application Data/Google/Chrome/Application/chrome.exe";

my @files = qw(
    icons/*.png
    _locales/*/messages.json
    960.css
    essentials.js
    LICENSE.txt
    manifest.json
    options.css
    options.html
    stroke.html
    stroke.js
);

my $dir = 'mouse-stroke';
my $tmp;
my ($src, $dst);
my $tmp2;
my ($manifest, $version);

#
# create temporary directory then copy all listed files 
#
do { $tmp = 'ms' . rand; } while (-e $tmp);

mkdir $tmp or die "Can't create temporary directory. $!";

foreach (@files) {

    $src = "$dir/$_";

    foreach (glob $src) {

        $dst = "$tmp/$_";
        $tmp2 = dirname($dst);

        if (not -e $tmp2) {
            mkpath $tmp2, 0, 0755 or die "Can't create directory $tmp2. $!";
        }

        copy $_, $dst or die "Can't copy file $_ to $dst. $!";

        #
        # get version, remember the manifest file name
        #
        if ('manifest.json' eq basename($dst)) {
            open $manifest, "<", $dst or die "Can't open manifest.json. $!";
            while (<$manifest>) {
                if (/^\s*"version"\s*:\s*"(.+)".*$/i) {
                    $version = $1;
                    print "Version: $version\n";
                    last;
                }
            }
            close $manifest;
            $manifest = $dst;
        }
    }
}

#
# generate crx package
#
print "Generating $dir-$version.crx\n";
0 == system ($CHROME,
             "--pack-extension=" . File::Spec->rel2abs("$tmp/$dir"),
             "--pack-extension-key=" . File::Spec->rel2abs("mouse-stroke.pem"))
    or die "Failed to pack extension. $!";

rename "$tmp/$dir.crx", "$dir-$version.crx" or die "Rename CRX failed. $!";

#
# generate zip package for https://chrome.google.com/extensions/
#
print "Generating $dir-$version.zip\n";
open FP, "<", $manifest or die "Can't open manifest.json for read. $!";
my @lines = <FP>;
close FP;
open FP, ">", $manifest or die "Can't open manifest.json for write. $!";
foreach (@lines) {
    print FP $_ unless /^\s*"update_url"\s*:\s*".+".*$/i;
}
close FP;

my $zip = Archive::Zip->new();
$zip->addTreeMatching("$tmp/$dir", undef, ".+");
$zip->writeToFileNamed("$dir-$version.zip");

#
# clean up
#
print "Removing temporary directory\n";
rmtree "$tmp" or die "Failed to remove the temporary directory. $!";

print "Done.\n";
